package com.yyk.yiliao.ui.trade;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import com.google.android.material.textfield.TextInputEditText;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.aa.OnClickFlagUtil;
import com.yyk.yiliao.util.BtnToEditListenerUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.glide.GlideUtils;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.OrderGettypeInfo;
import com.yyk.yiliao.bean.OrderMoneycarryInfo;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.UserbankMybankcardInfo;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 提现
 */
public class DrawCashActivity extends BaseActivity {

    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.ll_xzyh)
    LinearLayout llXzyh;
    @BindView(R.id.et_money)
    TextInputEditText etMoney;
    @BindView(R.id.tv_moneymessage)
    TextView tvMoneymessage;
    @BindView(R.id.tv_mpro)
    TextView tvMpro;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_cardtype_name)
    TextView tvCardtypeName;
    @BindView(R.id.tv_user_carry)
    TextView tvUserCarry;
    private int length;
    private int avoid;
    private int count;
    private float max;
    private float min;
    private float money;
    private float user_carry; //倍率
    //判断是否需要收手续费  1.没有手续费，2.有手续费，3.不通过无法交易
    private int drawFlag = 3;
    //判断是否需要收手续费  1.余额刚好，2.余额不足，3.不做任何操作
    private int moneyFlag = 3;
    private String cardId = "";
    private float remainMoney; //服务费金额
    private float realittMoney; //实际金额


    @Override
    public int getLayoutId() {
        return R.layout.activity_draw_cash;
    }

    @Override
    public void initView() {
        initToolbar();
        initEdittextview();
        initButton();

    }

    private void initButton() {
        BtnToEditListenerUtil.getInstance().setBtn(btNext).setBackgroud(R.color.blue_51, R.color.blue_89)
                .addEditView(etMoney)
                .build();
    }

    private void initEdittextview() {
//        InputFilter[] filters = {new EditInputFilter()};
//        etMoney.setFilters(filters);

        InputFilter[] filters = {new CashierInputFilter()};
        etMoney.setFilters(filters);


        etMoney.addTextChangedListener(new TextWatcher() {
            private float moneyFloat; //输入多少钱
            private String moneyString;
            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//                                String distanceString = decimalFormat.format(distanceValue) //format 返回的是字符串

            //之前
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //中间
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                length = s.length();
                if (length != 0) {
                    moneyString = String.valueOf(s);
                    moneyFloat = Float.valueOf(moneyString);
                }
            }

            //之后
            @Override
            public void afterTextChanged(Editable s) {
                if (length == 0) {
                    tvMoneymessage.setText("可用余额 " + decimalFormat.format(money) + "元");
                    tvMoneymessage.setTextColor(getResources().getColor(R.color.black_21));
                    drawFlag = 3;

                } else {
                    if (moneyFloat > max) {
                        tvMoneymessage.setText("最大提现金额为" + decimalFormat.format(max) + "元");
                        tvMoneymessage.setTextColor(getResources().getColor(R.color.red_e8));
                        drawFlag = 3;
                    } else if (moneyFloat < min) {
                        tvMoneymessage.setText("最小提现金额为" + decimalFormat.format(min) + "元");
                        tvMoneymessage.setTextColor(getResources().getColor(R.color.red_e8));
                        drawFlag = 3;

                    } else {
                        if (moneyFloat > money) {
                            tvMoneymessage.setText("可用余额不足 " + decimalFormat.format(moneyFloat) + "元");
                            tvMoneymessage.setTextColor(getResources().getColor(R.color.red_e8));
                            drawFlag = 3;

                        } else {
                            //没有免费提现次数 需要算手续费
                            if (avoid <= count) {
//                                ToastUtil.showShort(mActivity, "需要手续费");


                                //这个是余额中最大值可以体现的金额 ,向下取整-需要* 100)/100
                                float maxMoney = (float) ((Math.floor(money / (1 + user_carry) * 100)) / 100);
                                Logger.e("最大值余额" + maxMoney);
                                //正常服务费
                                float maxSefMoney = (float) ((Math.ceil(moneyFloat * user_carry * 100)) / 100);
                                //计算将要提现的手续费是否大于余额手续费，则按余额  规则收费
                                if (moneyFloat >= maxMoney) {
                                    float maxSxf = money - maxMoney;
                                    tvMoneymessage.setText("手续费 " + decimalFormat.format(maxSxf) + "元");
                                    Logger.e("手续费" + Math.ceil(maxSxf * 100) / 100);
                                    Logger.e("手续费 " + maxSxf + "元");
                                    tvMoneymessage.setTextColor(getResources().getColor(R.color.black_21));

                                    //刚好够提现 大于余额 需要从金额里面扣
                                    //扣除实际金额手续费
                                    remainMoney = maxSxf;
                                    //实际到账金额
                                    realittMoney = maxMoney;
                                    moneyFlag = 1;
                                }
                                //小于  正常收费
                                else {
//                                    float maxSef = moneyFloat - maxSefMoney;
                                    Logger.e("小于手续费" + Math.ceil(maxSefMoney * 100) / 100);
                                    Logger.e("手续费 " + maxSefMoney + "元");

                                    tvMoneymessage.setText("手续费 " + decimalFormat.format(maxSefMoney) + "元");
                                    tvMoneymessage.setTextColor(getResources().getColor(R.color.black_21));
                                    //扣除实际金额手续费
                                    remainMoney = maxSefMoney;
                                    //实际到账金额
                                    realittMoney = moneyFloat;
                                    moneyFlag = 2;
                                }

                                drawFlag = 2;
                            } else {
//                                ToastUtil.showShort(mActivity, "不需要手续费");
                                tvMoneymessage.setText("可用余额 " + decimalFormat.format(money) + "元");
                                tvMoneymessage.setTextColor(getResources().getColor(R.color.black_21));
                                drawFlag = 1;
                            }
                        }
                    }
                }


            }
        });
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("提现");
    }

    @Override
    public void initData() {

        initOrderGettype();
        initUserbankMybankcardt();
    }

    //银行卡列表
    private void initUserbankMybankcardt() {
        Map<String, String> map = new TreeMap<>();
        map.put("id", Hawk.get("uid") + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postUserbankMybankcard(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<UserbankMybankcardInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(UserbankMybankcardInfo info) {
                        Logger.e("我的银行卡列表" + info.toString());
                        if (info.getCode() == 1) {
                            List<UserbankMybankcardInfo.DataBean> data = info.getData();
                            UserbankMybankcardInfo.DataBean dataBean = data.get(0);
                            if (dataBean != null) {
                                GlideUtils.loadImage(mActivity, ApiService.BASE_URL + dataBean.getImg(), ivImg);
                                tvCardtypeName.setText(dataBean.getBank_name() + " (尾数" + dataBean.getNumberu() + ")");
                                cardId = String.valueOf(dataBean.getBindid());
                            } else {

                            }
                        }
                    }
                });


    }

    //体现金额介绍
    private void initOrderGettype() {
        Map<String, String> map = new TreeMap<>();
        map.put("id", Hawk.get("uid") + "");
        map.put("type_user", "1");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderGettype(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<OrderGettypeInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @SuppressLint("ResourceAsColor")
                    @Override
                    public void onNext(OrderGettypeInfo info) {
                        Logger.e("提现参数返回" + info.toString());
                        if (info.getCode() == 1) {
                            OrderGettypeInfo.DataBean data = info.getData();
                            //每月免费体现次数
                            avoid = data.getAvoid();
                            //已经体现几次
                            count = data.getCount();
                            //可体现最大
                            max = data.getMax();//如果要求精确4位就*10000然后/10000
                            //可体现最小
                            min = data.getMin();
                            String real_carry = data.getReal_carry();
                            //账户手续费倍率
                            user_carry = data.getUser_carry();
                            if (count >= avoid) {
                                tvUserCarry.setText("提现金额（收取" + user_carry*100 + "%服务费）");
                            } else {
                                tvUserCarry.setText("提现金额（本次提现可免手续费）");
                            }
                            //余额
                            money = data.getMoney();
                            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                            tvMoneymessage.setText("可用余额 " + decimalFormat.format(money) + "元");
                            tvMoneymessage.setTextColor(getResources().getColor(R.color.black_21));

                        }
                    }
                });
    }


    /**
     * 收费提示
     */
    private void showYinHangDialog(boolean flag) {
            /* 创建AlertDialog对象并显示 */
        final AlertDialog alertDialog = new AlertDialog.Builder(mActivity, R.style.MyDialog).create();
        alertDialog.show();
                        /* 添加对话框自定义布局 */
        alertDialog.setContentView(R.layout.alertdialog_popwindow_chargingtips);
    /* 获取对话框窗口 */
        Window window = alertDialog.getWindow();
//        /* 设置显示窗口的宽高 */
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        /* 设置窗口显示位置 */
        window.setGravity(Gravity.BOTTOM);
/*       将对话框的大小按屏幕大小的百分比设置
*/
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
        lp.height = (int) (display.getHeight() * 0.6); //设置高度
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; //设置宽度
        alertDialog.getWindow().setAttributes(lp);
        window.getDecorView().setPadding(0, 0, 0, 0);
        /* 还可以设置窗口显示动画 */
        window.setWindowAnimations(R.style.mystyle);
        TextView tv_realittmoeny = window.findViewById(R.id.tv_realittmoeny);
        TextView tv_remainmoney = window.findViewById(R.id.tv_remainmoney);
        TextView tv_next = window.findViewById(R.id.tv_next);
        TextView tv_show = window.findViewById(R.id.tv_show);
        if (flag) {
            tv_show.setVisibility(View.VISIBLE);
        } else {
            tv_show.setVisibility(View.GONE);
        }

        DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        //设置服务费
        tv_realittmoeny.setText(decimalFormat.format(realittMoney) + "");
        //设置到账金额
        tv_remainmoney.setText(decimalFormat.format(remainMoney) + "");
        tv_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 隐藏对话框
                alertDialog.dismiss();
                DialogUtil.getIntanse().showPayDialog(mActivity, new DialogUtil.PayListenter() {
                    @Override
                    public void onClick(String password, androidx.appcompat.app.AlertDialog dialog, TextView textView) {
                        Map<String, String> map = new TreeMap<>();
                        map.put("type_id", Hawk.get("uid") + "");
                        map.put("type_user", "1");
                        map.put("money", realittMoney + "");
                        map.put("cardid", cardId + "");

                        Logger.e("提现有手续费实际金额realitt" + realittMoney);
                        Logger.e("提现有手续费银行卡idcardId" + cardId);
                        map.put("pwd", password + "");
                        map.put("sign", Md5Util2.createSign(map));
                        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderMoneycarry(map)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .unsubscribeOn(Schedulers.io())
                                .subscribe(new Subscriber<OrderMoneycarryInfo>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(OrderMoneycarryInfo info) {
                                        Logger.e("患者提现" + info.toString());
                                        if (info.getCode() == 1) {
                                            startAct(DrawCashSuccendActivity.class, true);
                                            textView.setVisibility(View.GONE);
                                            dialog.dismiss();
                                        } else if (info.getCode() == 146) {
                                            textView.setVisibility(View.VISIBLE);
                                        } else {
                                            ToastUtil.showShort(mActivity, info.getMsg());
                                            textView.setVisibility(View.GONE);
                                        }
                                    }
                                });
                    }
                });

            }
        });
        /* 通过window找布局里的控件 */
        window.findViewById(R.id.iv_close).
                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 隐藏对话框
                        alertDialog.dismiss();
                    }
                });
        //取消dialog以外的区域的点击事件（默认为true）这里我们设置成false就ok啦
        alertDialog.setCanceledOnTouchOutside(false);


    }

    /**
     * 1.选择支付方式
     * 2.获取手机验证码
     * 3.全部提现
     *
     * @param view
     */
    @OnClick({R.id.ll_xzyh, R.id.bt_next, R.id.tv_mpro})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_xzyh:
                DialogUtil.getIntanse().showPayFangshiDialog(mActivity, true, true, new DialogUtil.SelectPayListenter() {
                    @Override
                    public void onClick(String img, String name, String id, String phone, androidx.appcompat.app.AlertDialog dialog) {
                        GlideUtils.loadImage(mActivity, ApiService.BASE_URL + img, ivImg);
                        tvCardtypeName.setText(name);
                        cardId = id;
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.bt_next:
                if (cardId.equals("") || cardId == null) {
                    ToastUtil.showShort(mActivity, "请选择银行卡");
                    return;
                }

                if (drawFlag == 3) {
                    //不能交易

                } else if (drawFlag == 2) {
                    if (moneyFlag == 1) {
                        showYinHangDialog(true);
                    } else if (moneyFlag == 2) {
                        showYinHangDialog(false);
                    } else {

                    }


                } else if (drawFlag == 1) {

                    //没有手续费
                    DialogUtil.getIntanse().showPayDialog(mActivity, new DialogUtil.PayListenter() {
                        @Override
                        public void onClick(String password, androidx.appcompat.app.AlertDialog dialog, TextView textView) {
                            Map<String, String> map = new TreeMap<>();
                            map.put("type_id", Hawk.get("uid") + "");
                            map.put("type_user", "1");
                            map.put("money", etMoney.getText().toString().trim() + "");
                            map.put("cardid", cardId + "");
                            Logger.e("cardId" + cardId);
                            map.put("pwd", password + "");
                            map.put("sign", Md5Util2.createSign(map));
                            RxUtils.getInstance().retrofit.create(ApiService.class).postOrderMoneycarry(map)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .unsubscribeOn(Schedulers.io())
                                    .subscribe(new Subscriber<OrderMoneycarryInfo>() {
                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(OrderMoneycarryInfo info) {
                                            Logger.e("患者提现" + info.toString());
                                            if (info.getCode() == 1) {
                                                startAct(DrawCashSuccendActivity.class, true);
                                                textView.setVisibility(View.GONE);
                                                dialog.dismiss();
                                            } else if (info.getCode() == 146) {
                                                textView.setVisibility(View.VISIBLE);
                                            } else {
                                                ToastUtil.showShort(mActivity, info.getMsg());
                                                textView.setVisibility(View.GONE);
                                            }
                                        }
                                    });
                        }
                    });

                }
                break;
            case R.id.tv_mpro:
                DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                realittMoney = (float) ((Math.floor(money / (1 + user_carry) * 100)) / 100);

                remainMoney = money - realittMoney;
                if (money > max) {
                    //因为最大值只可以设置2000
                    etMoney.setText(decimalFormat.format(money) + "");
                    tvMoneymessage.setText("最大提现金额为" + decimalFormat.format(max) + "元");
                    tvMoneymessage.setTextColor(getResources().getColor(R.color.red_e8));
                    drawFlag = 3;
                } else if (money < min) {
                    //没用
                    tvMoneymessage.setText("最小提现金额为" + decimalFormat.format(min) + "元");
                    tvMoneymessage.setTextColor(getResources().getColor(R.color.red_e8));
                    drawFlag = 3;

                } else {
                    tvMoneymessage.setText("手续费 " + decimalFormat.format(remainMoney) + "元");
                    etMoney.setText(decimalFormat.format(money) + "");
                    tvMoneymessage.setTextColor(getResources().getColor(R.color.black_21));
                }


                break;
        }
    }


}
